package com.probiz.estoresa.content.web.action;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.content.Newsletter;
import com.probiz.estore.common.model.content.NewsletterGroup;
import com.probiz.estore.common.model.content.TemplateFileFilter;
import com.probiz.estore.content.service.NewsletterGroupManager;
import com.probiz.estore.content.service.NewsletterManager;
import com.probiz.estore.core.controller.GenericStoreAdminController;

public class NewsletterController extends GenericStoreAdminController<Newsletter> {
    private NewsletterManager newsletterManager = null;
    
    private NewsletterGroupManager newsletterGroupManager = null;
    
	public void setNewsletterGroupManager(
			NewsletterGroupManager newsletterGroupManager) {
		this.newsletterGroupManager = newsletterGroupManager;
	}


	public void setNewsletterManager(NewsletterManager inMgr) {
        this.newsletterManager = inMgr;
    }

    
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(Newsletter entity) {
		return entity.getTitle();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = newsletterManager;
	}
	
	
	@Override
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		return super.defaultAction(request, response);
	}
	
	@Override
	protected Map<String,String> getSortMap(){
		Map<String,String> sortMap = new HashMap<String,String>();
		sortMap.put("1", "convert_gbk(title)");
		sortMap.put("2", "status");
		sortMap.put("3", "sendTime");
		sortMap.put("4", "updateTime");
		return sortMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#preSave(javax.servlet.http.HttpServletRequest,
	 *      java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected void preSave(HttpServletRequest request, Newsletter entity, BindException errors) {
		if(entity.getStatus()==null)
			entity.setStatus(Constants.STATUS_NOT_SENT);
		if(entity.getToAllCustomers()==null)
			entity.setToAllCustomers(Constants.FLAG_FALSE);
		//清除原有消息组，保存选取的消息组
		Set<NewsletterGroup> ngs = entity.getNewsletterGroups();
		if(ngs!=null)
			ngs.clear();
		String newsletterGroupIds [] = request.getParameterValues("newsletterGroupIds");
		for(String id:  newsletterGroupIds){
			NewsletterGroup newsletterGroup = newsletterGroupManager.getById(new Integer(id));
			if(newsletterGroup!=null)
				ngs.add(newsletterGroup);
		}
	}
	
	@Override
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) throws Exception { 
		Newsletter entity = formBackingObject(request);
		request.setAttribute("newsletter", entity);
		
		setRequestScopeVar(request, null);
		
		return new ModelAndView(formView);
	}
	
	private void setRequestScopeVar(HttpServletRequest request, java.util.Set<NewsletterGroup>  checkedNewsletterGroups){
		//消息组
		List<NewsletterGroup> newsletterGroups = newsletterGroupManager.getAllActiveNewsletterGroupList();
		//设置已被选的消息组
		if(checkedNewsletterGroups!=null){
			for(NewsletterGroup all: newsletterGroups){
				for(NewsletterGroup checked: checkedNewsletterGroups){
					if(all.getNewsletterGroupId().intValue()==checked.getNewsletterGroupId().intValue())
						all.setChecked(true);
				}
			}
		}else{
			String newsletterGroupIds [] = request.getParameterValues("newsletterGroupIds");
			if(newsletterGroupIds!=null)
			for(NewsletterGroup all: newsletterGroups){
				for(String id: newsletterGroupIds){
					if(all.getNewsletterGroupId().intValue()==Integer.valueOf(id))
						all.setChecked(true);
				}
			}
			
		}
		request.setAttribute("newsletterGroups", newsletterGroups);
		
		//模板列表
		Map<String,String> templatePathMap = new HashMap<String,String>();
		StringBuilder sb = new StringBuilder(ConfigUtil.getInstance()
				.getStoreFrontInstallationPath()).append("/velocity/newsletter");
		File file = new File(sb.toString());
		if (file.isDirectory()) {
			File[] subFiles = file.listFiles(new TemplateFileFilter(TemplateFileFilter.TEMPLATE_TYPE_VELOCITY));
			for (int i = 0; i < subFiles.length; i++) {
				File subFile = subFiles[i];
				templatePathMap.put("/newsletter/"+subFile.getName(), subFile.getName());
			}
		}
		request.setAttribute("templatePathMap", templatePathMap);
	}
	
	public ModelAndView testEmailNewsletter(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return null;
	}
	
	@Override
	public ModelAndView edit(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		Newsletter entity = formBackingObject(request);
		
		setRequestScopeVar(request, entity.getNewsletterGroups());
		
		ServletRequestDataBinder binder = this.getDefaultBinder(request,entity);
		BindException errors = new BindException(binder.getBindingResult());
		return showForm(request, errors);
	}
	
	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setRequestScopeVar(request, null);
		
		return super.save(request, response);
	}
	
	
	public ModelAndView testEmailNewletter(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		Newsletter entity = formBackingObject(request);
		request.setAttribute("newsletter", entity);
		
		ServletRequestDataBinder binder = this.getDefaultBinder(request,entity);
		BindException errors = new BindException(binder.getBindingResult());
		
		String _recipients = request.getParameter("recipients");
		if(_recipients!=null){
			String[] recipients = _recipients.split("[,|;]");
			if(recipients!=null && recipients.length>0){
				newsletterManager.testEmailNewletter(entity, recipients);
				saveMessage(request, getMessage("newsletter.testEmailNewsletter.success"));
			}
		}
		
		setRequestScopeVar(request, null);
		
		return showForm(request, errors);
	}


}
